package com.nextgen.services;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nextgen.bean.CustomerDetails;
import com.nextgen.bean.Role;

@Service
@Transactional(readOnly = true)
public class CustomerAuthenticationService implements UserDetailsService {

	@Autowired
	private CustomerDetailsService customerDetails;
	@Autowired
	private RoleService roleService;
	
	
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		CustomerDetails domainUser = customerDetails.getCustomerDetailsById(username);
		
		
		return new User(
				domainUser.getUserId(), 
				domainUser.getPassword().toLowerCase(),
				domainUser.isActive(),
				domainUser.isActive(),
				domainUser.isActive(),
				domainUser.isActive(),
				getAuthorities(domainUser.getUserId()));
	}

	/**
	 * Retrieves a collection of {@link GrantedAuthority} based on a numerical role
	 * @param role the numerical role
	 * @return a collection of {@link GrantedAuthority
	 */
	public Collection<? extends GrantedAuthority> getAuthorities(String userName) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(userName));
		return authList;
	}

	/**
	 * Wraps {@link String} roles to {@link SimpleGrantedAuthority} objects
	 * @param roles {@link String} of roles
	 * @return list of granted authorities
	 */
	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
	
	/**
	 * Converts a numerical role to an equivalent list of roles
	 * @param role the numerical role
	 * @return list of roles as as a list of {@link String}
	 */
	public List<String> getRoles(String userName) {
		List<Role> roleList = roleService.getRoleByUserName(userName);
		return getRoles(roleList);
	}

	private List<String> getRoles(List<Role> roleList) {
		List<String> roles = new ArrayList<String>();
		for(Role role: roleList) {
			roles.add(role.getRoleDescription());
		}
		return roles;
	}

}
